<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档涉密内容处理系统</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 20px;
            position: relative;
        }
        
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="black" opacity="0.05"/><circle cx="75" cy="75" r="1" fill="black" opacity="0.05"/><circle cx="50" cy="10" r="0.5" fill="black" opacity="0.05"/><circle cx="10" cy="60" r="0.5" fill="black" opacity="0.05"/><circle cx="90" cy="40" r="0.5" fill="black" opacity="0.05"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            pointer-events: none;
            z-index: -1;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.15);
            overflow: hidden;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .header::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: float 6s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translate(-50%, -50%) rotate(0deg); }
            50% { transform: translate(-50%, -50%) rotate(180deg); }
        }
        
        .header h1 {
            font-size: 2.8em;
            margin-bottom: 15px;
            font-weight: 700;
            position: relative;
            z-index: 1;
            color: #2c3e50;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.95;
            position: relative;
            z-index: 1;
        }
        
        .content {
            padding: 50px;
        }
        
        .upload-section {
            margin-bottom: 40px;
        }
        
        .form-group {
            margin-bottom: 30px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 12px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 1.1em;
        }
        
        .file-upload-area {
            position: relative;
            border: 3px dashed #bdc3c7;
            border-radius: 15px;
            padding: 40px 20px;
            text-align: center;
            background: linear-gradient(145deg, #f8f9fa, #e9ecef);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .file-upload-area:hover {
            border-color: #667eea;
            background: linear-gradient(145deg, #f0f4ff, #e8f2ff);
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
        }
        
        .file-upload-area.dragover {
            border-color: #27ae60;
            background: linear-gradient(145deg, #e8f5e8, #d4edda);
        }
        
        .file-upload-icon {
            font-size: 3em;
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .file-upload-text {
            font-size: 1.2em;
            color: #34495e;
            margin-bottom: 10px;
        }
        
        .file-upload-hint {
            font-size: 0.9em;
            color: #7f8c8d;
        }
        
        .file-input {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }
        
        .selected-files {
            margin-top: 15px;
        }
        
        .file-item {
            padding: 15px;
            background: #e8f5e8;
            border-radius: 10px;
            border-left: 4px solid #27ae60;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .file-item:hover {
            background: #d5f0d5;
            transform: translateX(5px);
        }
        
        .file-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .file-name {
            font-weight: 600;
            color: #2c3e50;
        }
        
        .file-size {
            color: #7f8c8d;
            font-size: 0.9em;
        }
        
        .file-remove {
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .file-remove:hover {
            background: #c0392b;
            transform: scale(1.1);
        }
        
        .files-summary {
            margin-top: 15px;
            padding: 10px 15px;
            background: #f8f9fa;
            border-radius: 8px;
            color: #6c757d;
            font-size: 0.9em;
            display: none;
        }
        
        .files-summary.show {
            display: block;
        }
        
        .text-input {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e0e6ed;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #fff;
        }
        
        .text-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .btn-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 30px;
        }
        
        .btn {
            padding: 18px 30px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            transition: all 0.3s ease;
            transform: translate(-50%, -50%);
        }
        
        .btn:hover::before {
            width: 300px;
            height: 300px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            box-shadow: 0 8px 25px rgba(52, 152, 219, 0.3);
        }
        
        .btn-primary:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 35px rgba(52, 152, 219, 0.4);
            background: linear-gradient(135deg, #2980b9 0%, #1f5f8b 100%);
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #5dade2 0%, #3498db 100%);
            color: white;
            box-shadow: 0 8px 25px rgba(93, 173, 226, 0.3);
        }
        
        .btn-secondary:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 35px rgba(93, 173, 226, 0.4);
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
            color: white;
            box-shadow: 0 8px 25px rgba(39, 174, 96, 0.3);
        }
        
        .btn-success:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 35px rgba(39, 174, 96, 0.4);
            background: linear-gradient(135deg, #229954 0%, #27ae60 100%);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }
        
        .results {
            margin-top: 40px;
            padding: 30px;
            background: linear-gradient(145deg, #f8f9fa, #e9ecef);
            border-radius: 15px;
            display: none;
            border: 1px solid #dee2e6;
        }
        
        .results.show {
            display: block;
            animation: slideIn 0.5s ease;
        }
        
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .results h3 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 1.4em;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .sensitive-item {
            background: white;
            padding: 20px;
            margin-bottom: 15px;
            border-radius: 12px;
            border-left: 5px solid #e74c3c;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: transform 0.2s ease;
        }
        
        .sensitive-item:hover {
            transform: translateX(5px);
        }
        
        .sensitive-item strong {
            color: #e74c3c;
        }
        
        .download-section {
            margin-top: 30px;
            padding: 30px;
            background: linear-gradient(135deg, #00b894 0%, #00a085 100%);
            border-radius: 15px;
            text-align: center;
            color: white;
            display: none;
        }
        
        .download-section.show {
            display: block;
            animation: slideIn 0.5s ease;
        }
        
        .download-section h3 {
            font-size: 1.5em;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .download-section p {
            margin-bottom: 25px;
            opacity: 0.9;
        }
        
        .download-btn {
            background: linear-gradient(45deg, #27ae60, #2ecc71);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 18px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(39, 174, 96, 0.4);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }
        
        .download-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(39, 174, 96, 0.6);
            background: linear-gradient(45deg, #229954, #27ae60);
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }
        
        .loading.show {
            display: block;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .loading-text {
            font-size: 1.1em;
            color: #667eea;
            font-weight: 500;
        }
        
        .alert {
            padding: 20px;
            margin-bottom: 25px;
            border-radius: 12px;
            display: none;
            position: relative;
            overflow: hidden;
        }
        
        .alert.show {
            display: block;
            animation: slideIn 0.3s ease;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-label {
            color: #7f8c8d;
            margin-top: 5px;
        }
        
        @media (max-width: 768px) {
            .content {
                padding: 30px 20px;
            }
            
            .btn-group {
                grid-template-columns: 1fr;
            }
            
            .header h1 {
                font-size: 2.2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-shield-alt"></i> 文档涉密内容处理系统</h1>
            <p>智能识别并加密文档中的敏感信息，保护您的数据安全</p>
        </div>
        
        <div class="content">
            <div class="alert" id="alertBox"></div>
            
            <div class="upload-section">
                <div class="form-group">
                    <label for="fileInput">
                        <i class="fas fa-file-word"></i> 选择Word文档（支持多文件）
                    </label>
                    <div class="file-upload-area" id="fileUploadArea">
                        <div class="file-upload-icon">
                            <i class="fas fa-cloud-upload-alt"></i>
                        </div>
                        <div class="file-upload-text">点击选择文件或拖拽到此处</div>
                        <div class="file-upload-hint">支持 .doc 和 .docx 格式，每个文件最大 50MB，支持多文件选择</div>
                        <input type="file" id="fileInput" class="file-input" accept=".doc,.docx" multiple>
                    </div>
                    <div class="selected-files" id="selectedFiles">
                        <!-- 多文件列表将在这里显示 -->
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="sensitiveWords">
                        <i class="fas fa-tags"></i> 敏感词列表
                    </label>
                    <input type="text" 
                           id="sensitiveWords" 
                           class="text-input" 
                           placeholder="请输入敏感词，用逗号分隔"
                           value="">
                </div>
                
                <div class="btn-group" style="grid-template-columns: 1fr 1fr 1fr;">
                    <button class="btn btn-secondary" onclick="identifyOnly()" id="identifyBtn">
                        <i class="fas fa-search"></i> 识别敏感内容
                    </button>
                    <button class="btn btn-primary" onclick="processDocument()" id="processBtn">
                        <i class="fas fa-lock"></i> 处理并加密
                    </button>
                    <button class="btn btn-success" onclick="decryptDocument()" id="decryptBtn">
                        <i class="fas fa-unlock"></i> 解密文档
                    </button>
                </div>
            </div>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>
                <div class="loading-text">正在处理文档，请稍候...</div>
            </div>
            
            <div class="results" id="results">
                <h3><i class="fas fa-search"></i> 识别结果</h3>
                <div id="sensitiveList"></div>
                <div class="stats-grid" id="statsGrid" style="display: none;">
                    <div class="stat-card">
                        <div class="stat-number" id="totalSensitive">0</div>
                        <div class="stat-label">敏感词总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="uniqueWords">0</div>
                        <div class="stat-label">不同敏感词</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalParagraphs">0</div>
                        <div class="stat-label">涉及段落</div>
                    </div>
                </div>
            </div>
            
            <div class="download-section" id="downloadSection" style="display: none;">
                <h3><i class="fas fa-check-circle"></i> 处理完成</h3>
                <p>文档已成功加密处理，敏感内容已被安全加密。点击下方按钮下载处理后的文件。</p>
                <button class="download-btn" id="downloadBtn">
                    <i class="fas fa-download"></i> 下载加密文档
                </button>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = '/api/document';
        let processedFileData = null;
        let processedFileName = null;
        let selectedFiles = [];

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            initializeFileUpload();
        });

        function initializeFileUpload() {
            const fileUploadArea = document.getElementById('fileUploadArea');
            const fileInput = document.getElementById('fileInput');

            // 文件选择事件
            fileInput.addEventListener('change', function(e) {
                handleMultipleFileSelect(e.target.files);
            });

            // 拖拽事件
            fileUploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                fileUploadArea.classList.add('dragover');
            });

            fileUploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                fileUploadArea.classList.remove('dragover');
            });

            fileUploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                fileUploadArea.classList.remove('dragover');
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleMultipleFileSelect(files);
                }
            });
        }

        function handleMultipleFileSelect(files) {
            const validFiles = [];
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 验证文件类型
                const validTypes = [
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                ];
                
                if (!validTypes.includes(file.type) && !file.name.match(/\.(doc|docx)$/i)) {
                    showAlert(`文件 "${file.name}" 不是有效的Word文档格式`, 'error');
                    continue;
                }

                // 验证文件大小 (50MB)
                if (file.size > 50 * 1024 * 1024) {
                    showAlert(`文件 "${file.name}" 大小超过 50MB 限制`, 'error');
                    continue;
                }

                // 检查是否已经选择了相同的文件
                const isDuplicate = selectedFiles.some(selectedFile => 
                    selectedFile.name === file.name && selectedFile.size === file.size
                );
                
                if (isDuplicate) {
                    showAlert(`文件 "${file.name}" 已经选择过了`, 'error');
                    continue;
                }

                validFiles.push(file);
            }

            // 添加有效文件到选择列表
            selectedFiles.push(...validFiles);
            updateFileDisplay();
            updateButtonStates();
        }

        function updateFileDisplay() {
            const selectedFilesContainer = document.getElementById('selectedFiles');
            
            if (selectedFiles.length === 0) {
                selectedFilesContainer.innerHTML = '';
                return;
            }

            let html = '';
            selectedFiles.forEach((file, index) => {
                html += `
                    <div class="file-item" data-index="${index}">
                        <div class="file-info">
                            <i class="fas fa-file-word" style="color: #2980b9;"></i>
                            <div>
                                <div class="file-name">${file.name}</div>
                                <div class="file-size">${formatFileSize(file.size)}</div>
                            </div>
                        </div>
                        <button class="file-remove" onclick="removeFile(${index})" title="移除文件">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                `;
            });

            // 添加文件汇总信息
            const totalSize = selectedFiles.reduce((sum, file) => sum + file.size, 0);
            html += `
                <div class="files-summary show">
                    <i class="fas fa-info-circle"></i> 
                    已选择 ${selectedFiles.length} 个文件，总大小: ${formatFileSize(totalSize)}
                </div>
            `;

            selectedFilesContainer.innerHTML = html;
        }

        function removeFile(index) {
            selectedFiles.splice(index, 1);
            updateFileDisplay();
            updateButtonStates();
        }

        function updateButtonStates() {
            const hasFiles = selectedFiles.length > 0;
            document.getElementById('identifyBtn').disabled = !hasFiles;
            document.getElementById('processBtn').disabled = !hasFiles;
            document.getElementById('decryptBtn').disabled = !hasFiles;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        function showAlert(message, type = 'success') {
            const alertBox = document.getElementById('alertBox');
            alertBox.className = `alert alert-${type} show`;
            alertBox.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}"></i> ${message}`;
            
            setTimeout(() => {
                alertBox.classList.remove('show');
            }, 5000);
        }
        
        function showLoading(show = true) {
            const loading = document.getElementById('loading');
            loading.classList.toggle('show', show);
            // 禁用/启用按钮
            document.getElementById('identifyBtn').disabled = show;
            document.getElementById('processBtn').disabled = show;
        }
        
        function showResults(show = true) {
            const results = document.getElementById('results');
            results.classList.toggle('show', show);
        }
        
        function showDownloadSection(show = true) {
            const downloadSection = document.getElementById('downloadSection');
            downloadSection.style.display = show ? 'block' : 'none';
            if (show) {
                downloadSection.classList.add('show');
            }
        }
        
        function validateInput() {
            if (selectedFiles.length === 0) {
                showAlert('请选择要处理的文档', 'error');
                return false;
            }
            
            const sensitiveWords = document.getElementById('sensitiveWords').value.trim();
            if (!sensitiveWords) {
                showAlert('请输入敏感词列表', 'error');
                return false;
            }
            
            return true;
        }
        
        function validateFileOnly() {
            if (selectedFiles.length === 0) {
                showAlert('请选择要处理的文档', 'error');
                return false;
            }
            
            return true;
        }
        
        async function identifyOnly() {
            if (!validateInput()) return;
            
            const sensitiveWords = document.getElementById('sensitiveWords').value.trim();
            
            showLoading(true);
            showResults(false);
            showDownloadSection(false);
            
            try {
                const allSensitiveContent = [];
                let totalCount = 0;
                
                // 处理每个文件
                for (let i = 0; i < selectedFiles.length; i++) {
                    const file = selectedFiles[i];
                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('sensitiveWords', sensitiveWords);
                    
                    const response = await fetch(`${API_BASE}/identify`, {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        // 为每个敏感内容添加文件名信息
                        const contentWithFileName = result.sensitiveContent.map(item => ({
                            ...item,
                            fileName: file.name
                        }));
                        allSensitiveContent.push(...contentWithFileName);
                        totalCount += result.count;
                    } else {
                        showAlert(`处理文件 "${file.name}" 时出错: ${result.message}`, 'error');
                    }
                }
                
                displayMultiFileSensitiveContent(allSensitiveContent);
                showAlert(`识别完成，在 ${selectedFiles.length} 个文件中发现 ${totalCount} 处敏感内容`);
                showResults(true);
                
            } catch (error) {
                showAlert('请求失败: ' + error.message, 'error');
            } finally {
                showLoading(false);
            }
        }
        
        async function processDocument() {
            if (!validateInput()) return;
            
            const sensitiveWords = document.getElementById('sensitiveWords').value.trim();
            
            showLoading(true);
            showResults(false);
            showDownloadSection(false);
            
            try {
                const allSensitiveContent = [];
                const processedFiles = [];
                let totalSensitiveCount = 0;
                
                // 处理每个文件
                for (let i = 0; i < selectedFiles.length; i++) {
                    const file = selectedFiles[i];
                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('sensitiveWords', sensitiveWords);
                    
                    const response = await fetch(`${API_BASE}/analyze-and-process`, {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        // 为每个敏感内容添加文件名信息
                        const contentWithFileName = result.sensitiveContent.map(item => ({
                            ...item,
                            fileName: file.name
                        }));
                        allSensitiveContent.push(...contentWithFileName);
                        totalSensitiveCount += result.sensitiveCount;
                        
                        // 保存处理后的文件信息
                        if (result.processedFileData && result.processedFileName) {
                            processedFiles.push({
                                data: result.processedFileData,
                                fileName: result.processedFileName,
                                originalFileName: file.name
                            });
                        }
                    } else {
                        showAlert(`处理文件 "${file.name}" 时出错: ${result.message}`, 'error');
                    }
                }
                
                displayMultiFileSensitiveContent(allSensitiveContent);
                showResults(true);
                
                // 设置多文件下载功能
                if (processedFiles.length > 0) {
                    setupMultiFileDownload(processedFiles);
                    showDownloadSection(true);
                }
                
                showAlert(`处理完成，在 ${selectedFiles.length} 个文件中发现并加密了 ${totalSensitiveCount} 处敏感内容`);
                
            } catch (error) {
                showAlert('请求失败: ' + error.message, 'error');
            } finally {
                showLoading(false);
            }
        }
        
        async function decryptDocument() {
            if (!validateFileOnly()) return;
            
            showLoading(true);
            showResults(false);
            showDownloadSection(false);
            
            try {
                const decryptedFiles = [];
                
                // 解密每个文件
                for (let i = 0; i < selectedFiles.length; i++) {
                    const file = selectedFiles[i];
                    const formData = new FormData();
                    formData.append('file', file);
                    
                    const response = await fetch(`${API_BASE}/decrypt`, {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        // 保存解密后的文件信息
                        if (result.decryptedFileData && result.decryptedFileName) {
                            decryptedFiles.push({
                                data: result.decryptedFileData,
                                fileName: result.decryptedFileName,
                                originalFileName: file.name
                            });
                        }
                    } else {
                        showAlert(`解密文件 "${file.name}" 时出错: ${result.message}`, 'error');
                    }
                }
                
                // 设置多文件下载功能
                if (decryptedFiles.length > 0) {
                    setupMultiFileDownload(decryptedFiles);
                    showDownloadSection(true);
                    
                    // 更新下载按钮文本
                    const downloadBtn = document.getElementById('downloadBtn');
                    downloadBtn.innerHTML = '<i class="fas fa-download"></i> 下载解密文档';
                    
                    // 更新下载区域标题和描述
                    const downloadSection = document.getElementById('downloadSection');
                    downloadSection.querySelector('h3').innerHTML = '<i class="fas fa-unlock"></i> 解密完成';
                    downloadSection.querySelector('p').textContent = '文档已成功解密，加密内容已被还原。点击下方按钮下载解密后的文件。';
                    
                    showAlert(`解密完成，成功解密了 ${decryptedFiles.length} 个文件`);
                } else {
                    showAlert('没有文件被成功解密', 'error');
                }
                
            } catch (error) {
                showAlert('请求失败: ' + error.message, 'error');
            } finally {
                showLoading(false);
            }
        }
        
        function displaySensitiveContent(sensitiveContent) {
            const sensitiveList = document.getElementById('sensitiveList');
            const statsGrid = document.getElementById('statsGrid');
            
            if (!sensitiveContent || sensitiveContent.length === 0) {
                sensitiveList.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #27ae60;">
                        <i class="fas fa-check-circle" style="font-size: 3em; margin-bottom: 15px;"></i>
                        <h3>未发现敏感内容</h3>
                        <p>您的文档很安全，没有检测到敏感信息。</p>
                    </div>
                `;
                statsGrid.style.display = 'none';
                return;
            }
            
            let html = '';
            const uniqueWords = new Set();
            const paragraphs = new Set();
            
            sensitiveContent.forEach((item, index) => {
                uniqueWords.add(item.sensitiveWord || item.word);
                paragraphs.add(item.paragraphIndex);
                
                html += `
                    <div class="sensitive-item">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <strong style="color: #e74c3c; font-size: 1.1em;">
                                <i class="fas fa-exclamation-triangle"></i> ${item.sensitiveWord || item.word}
                            </strong>
                            <span style="background: #e74c3c; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.8em;">
                                第${(item.paragraphIndex || 0) + 1}段
                            </span>
                        </div>
                        <div style="color: #666; line-height: 1.5;">
                            <strong>发现文本:</strong> ${item.foundText || item.word}<br>
                            <strong>位置:</strong> 字符位置 ${item.startPosition || '?'}-${item.endPosition || '?'}<br>
                            <strong>上下文:</strong> ...${item.context}...
                        </div>
                    </div>
                `;
            });
            
            sensitiveList.innerHTML = html;
            
            // 更新统计信息
            document.getElementById('totalSensitive').textContent = sensitiveContent.length;
            document.getElementById('uniqueWords').textContent = uniqueWords.size;
            document.getElementById('totalParagraphs').textContent = paragraphs.size;
            statsGrid.style.display = 'grid';
        }
        
        function displayMultiFileSensitiveContent(allSensitiveContent) {
            const sensitiveList = document.getElementById('sensitiveList');
            const statsGrid = document.getElementById('statsGrid');
            
            if (!allSensitiveContent || allSensitiveContent.length === 0) {
                sensitiveList.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #27ae60;">
                        <i class="fas fa-check-circle" style="font-size: 3em; margin-bottom: 15px;"></i>
                        <h3>未发现敏感内容</h3>
                        <p>您的文档很安全，没有检测到敏感信息。</p>
                    </div>
                `;
                statsGrid.style.display = 'none';
                return;
            }
            
            let html = '';
            const uniqueWords = new Set();
            const paragraphs = new Set();
            const fileGroups = {};
            
            // 按文件分组
            allSensitiveContent.forEach(item => {
                if (!fileGroups[item.fileName]) {
                    fileGroups[item.fileName] = [];
                }
                fileGroups[item.fileName].push(item);
                uniqueWords.add(item.sensitiveWord || item.word);
                paragraphs.add(`${item.fileName}-${item.paragraphIndex}`);
            });
            
            // 为每个文件显示敏感内容
            Object.keys(fileGroups).forEach(fileName => {
                html += `
                    <div style="margin-bottom: 30px; border: 1px solid #ddd; border-radius: 10px; overflow: hidden;">
                        <div style="background: #f8f9fa; padding: 15px; border-bottom: 1px solid #ddd;">
                            <h4 style="margin: 0; color: #2c3e50; display: flex; align-items: center; gap: 10px;">
                                <i class="fas fa-file-word" style="color: #2980b9;"></i>
                                ${fileName}
                                <span style="background: #e74c3c; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.8em; margin-left: auto;">
                                    ${fileGroups[fileName].length} 处敏感内容
                                </span>
                            </h4>
                        </div>
                        <div style="padding: 15px;">
                `;
                
                fileGroups[fileName].forEach((item, index) => {
                    html += `
                        <div class="sensitive-item" style="margin-bottom: 15px; border-left-color: #e74c3c;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                <strong style="color: #e74c3c; font-size: 1.1em;">
                                    <i class="fas fa-exclamation-triangle"></i> ${item.sensitiveWord || item.word}
                                </strong>
                                <span style="background: #e74c3c; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.8em;">
                                    第${(item.paragraphIndex || 0) + 1}段
                                </span>
                            </div>
                            <div style="color: #666; line-height: 1.5;">
                                <strong>发现文本:</strong> ${item.foundText || item.word}<br>
                                <strong>位置:</strong> 字符位置 ${item.startPosition || '?'}-${item.endPosition || '?'}<br>
                                <strong>上下文:</strong> ...${item.context}...
                            </div>
                        </div>
                    `;
                });
                
                html += `
                        </div>
                    </div>
                `;
            });
            
            sensitiveList.innerHTML = html;
            
            // 更新统计信息
            document.getElementById('totalSensitive').textContent = allSensitiveContent.length;
            document.getElementById('uniqueWords').textContent = uniqueWords.size;
            document.getElementById('totalParagraphs').textContent = paragraphs.size;
            statsGrid.style.display = 'grid';
        }
        
        function setupMultiFileDownload(processedFiles) {
            const downloadBtn = document.getElementById('downloadBtn');
            
            if (processedFiles.length === 1) {
                // 单文件下载
                downloadBtn.onclick = function() {
                    downloadFile(processedFiles[0].data, processedFiles[0].fileName);
                };
            } else {
                // 多文件下载 - 创建ZIP
                downloadBtn.onclick = function() {
                    downloadMultipleFiles(processedFiles);
                };
                downloadBtn.innerHTML = '<i class="fas fa-download"></i> 下载所有文件 (ZIP)';
            }
        }
        
        function setupDownload() {
            const downloadBtn = document.getElementById('downloadBtn');
            
            downloadBtn.onclick = function() {
                if (processedFileData && processedFileName) {
                    downloadFile(processedFileData, processedFileName);
                } else {
                    showAlert('没有可下载的文件', 'error');
                }
            };
        }
        
        async function downloadMultipleFiles(processedFiles) {
            try {
                // 如果只有一个文件，直接下载
                if (processedFiles.length === 1) {
                    downloadFile(processedFiles[0].data, processedFiles[0].fileName);
                    return;
                }
                
                // 多个文件时，逐个下载
                for (let i = 0; i < processedFiles.length; i++) {
                    const file = processedFiles[i];
                    setTimeout(() => {
                        downloadFile(file.data, file.fileName);
                    }, i * 500); // 延迟下载避免浏览器阻止
                }
                
                showAlert(`开始下载 ${processedFiles.length} 个文件，请注意浏览器下载提示`);
            } catch (error) {
                showAlert('批量下载失败: ' + error.message, 'error');
            }
        }
        
        function downloadFile(base64Data, fileName) {
            try {
                // 将Base64数据转换为Blob
                const byteCharacters = atob(base64Data);
                const byteNumbers = new Array(byteCharacters.length);
                for (let i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                const byteArray = new Uint8Array(byteNumbers);
                const blob = new Blob([byteArray], { 
                    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
                });
                
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                showAlert('文件下载成功！加密文档已保存到您的下载文件夹');
            } catch (error) {
                showAlert('下载失败: ' + error.message, 'error');
                console.error('Download error:', error);
            }
        }
    </script>
</body>
</html>